init();

// re initialize after DOM modification
$('body').bind('DOMSubtreeModified', function() {
	init();
});

function init() {
	// find elements <span> with date content
	$('span').each(function(index) {
		var txt = $(this).text();
		if (isDate(txt)) {
			// modify elements <span>
			var gae = parseTime(txt);
			$(this).text(getFormatDateString(gae) + " " + txt);
		}
	});
}

function parseTime(timeNodeValue) {
	var year = timeNodeValue.substring(0, 4);
	var month = timeNodeValue.substring(5, 7);
	var day = timeNodeValue.substring(8, 10);
	var hour = timeNodeValue.substring(11, 13);
	var min = timeNodeValue.substring(14, 16);
	var sec = timeNodeValue.substring(17, 19);
	var ms = timeNodeValue.substring(20, 23);
	// Month is 0-11 in JavaScript
	var date = new Date(year, month - 1, day, hour, min, sec);
	date.setMilliseconds(ms);
	return date;
}

function isDate(data) {
	return /^\d{4}-\d{2}-\d{2}.*/.test(data);
}

function getFormatDateString(date) {
	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	var monthnumber = date.getMonth() + 1;
	var monthday = date.getDate();
	var year = date.getFullYear();
	var now = new Date();

	var delta = now.getTime() - date.getTime();
	var daysAgo = (delta / 24 * 3600000);
	daysAgo = daysAgo - (hoursAgo % 1);

	var ago = "";
	
	if (daysAgo > 0) {
		ago = daysAgo + " day" + (hoursAgo > 1 ? "s" : "");
	} else {
		var hoursAgo = (delta / 3600000);
		hoursAgo = hoursAgo - (hoursAgo % 1);
		if (hoursAgo > 0) {
			ago = hoursAgo + " hour" + (hoursAgo > 1 ? "s" : "");
		} else {
			var minsAgo = (delta / 60000);
			minsAgo = minsAgo - (minsAgo % 1);
			if (minsAgo > 0) {
				ago = minsAgo + " minute" + (minsAgo > 1 ? "s" : "");
			} else {
				var secondsAgo = extround(delta / 1000, 1000);
				ago = secondsAgo + " second" + (secondsAgo > 1 ? "s" : "");
				;
			}
		}
	}
	ago += " ago";
	return ago;
}

function extround(zahl, n_stelle) {
	zahl = (Math.round(zahl * n_stelle) / n_stelle);
	return zahl;
}
